<?php

namespace Biz\Criteria\Site;

use Lumen\Repository\Contracts\CriterionContract;

/**
 * LocaleFilterCriterion.
 *
 * @license [http://www.85do.com] [杭州永奥网络科技有限公司]
 * @copyright Copyright (c) 2018-2026 Hangzhou Yongao Technology Co., Ltd. All rights reserved.
 */
class LocaleFilterCriterion implements CriterionContract
{
    /**
     * @var mixed
     */
    protected $locale;

    /**
     * @var mixed
     */
    protected $app_locale;

    /**
     * LocaleFilterCriterion constructor.
     *
     * @param string $locale
     */
    public function __construct(string $locale = null)
    {
        $this->locale     = $locale;
        $this->app_locale = config('app.locale');
    }

    /**
     * Apply current criterion to the given query and return query.
     *
     * @param \Illuminate\Database\Eloquent\Model            $model
     * @param \Lumen\Repository\Contracts\RepositoryContract $repository
     *
     * @return \Illuminate\Database\Eloquent\Model
     */
    public function apply($model, $repository)
    {
        $model = $model->whereHas('translations', function ($query) {
            $query->where('locale', '=', $this->locale ?? $this->app_locale);
        });

        return $model;
    }
}
